﻿using System.ComponentModel;
using IrcBot.IrcSender;
using IrcBot.Listener;

namespace IrcBot
{
    public class IrcBot
    {
        private static SocketListener _listener;
        private static BackgroundWorker _worker;

        #region Singleton Members

        private static IrcBot _instance;
        private BotController _botController;

        public static IrcBot GetInstance()
        {
            if (_instance == null)
            {
                _instance = new IrcBot();
            }

            return _instance;
        }

        private IrcBot()
        { }

        #endregion

        #region Main thread

        public void StartListening()
        {
            if (_worker == null)
            {
                _worker = new BackgroundWorker();
                _worker.DoWork += StartListening;
                _worker.WorkerReportsProgress = false;
                _worker.WorkerSupportsCancellation = true;
            }

            _worker.RunWorkerAsync();
        }

        public void StopListening()
        {
            _listener.Dispose();
            _worker.CancelAsync();
            _worker.Dispose();
        }

        #endregion

        #region Listener thread

        private void StartListening(object sender, DoWorkEventArgs e)
        {
            _listener = new SocketListener();

            _listener.OnStartListening += OnStartListening;
            _listener.OnStopListening += OnStopListening;

            _botController = BotController.GetInstance();
            _botController.OnBotCreated += OnBotCreated;
            _botController.OnBotKilled += OnBotKilled;
            _botController.OnBotError += OnBotError;
        }

        #endregion


        public event MessageEventHandler OnStartListening;
        public event MessageEventHandler OnStopListening;
        public event MessageEventHandler OnBotCreated;
        public event MessageEventHandler OnBotKilled;
        public event MessageEventHandler OnBotError;
    }
}
